package service

import (
	"github.com/gogf/gf/v2/frame/g"
	"golang.org/x/net/context"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	GenInt64Id "lot_admin_api/utility/genInt64IdOfString"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"
)

type sHelpDoc struct{}

var insHelpDoc = sHelpDoc{}

func HelpDoc() *sHelpDoc {
	return &insHelpDoc
}

// AddHelpDoc 新增帮助文档
func (s *sHelpDoc) AddHelpDoc(ctx context.Context, req *model.LotHelpDocInfoAndIdRes) (lastInsertId string, err error) {
	req.Id = GenInt64Id.GenInt64IdOfString() // 赋值id
	r := g.RequestFromCtx(ctx)
	if _, err = dao.LotHelp.Ctx(ctx).OmitEmpty().Save(&req); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "保存帮助文档失败")
	}
	return req.Id, err
}

// EditHelpDoc 编辑帮助文档
func (s *sHelpDoc) EditHelpDoc(ctx context.Context, req *model.LotHelpDocInfoAndIdRes) (lastInsertId string, err error) {
	_, _ = s.SearchHelpDocInfo(ctx, req.Id) // 查询是否有当前文档
	r := g.RequestFromCtx(ctx)
	if _, err = dao.LotHelp.Ctx(ctx).OmitEmpty().Where("id", req.Id).Update(&req); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "编辑帮助文档失败")
	}
	return req.Id, err
}

// DeleteHelpDoc 删除帮助文档
func (s *sHelpDoc) DeleteHelpDoc(ctx context.Context, id string) (lastInsertId string, err error) {
	_, _ = s.SearchHelpDocInfo(ctx, id) // 查询是否有当前文档
	r := g.RequestFromCtx(ctx)
	if _, err = dao.LotHelp.Ctx(ctx).Where("id", id).Delete(); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "删除帮助文档失败")
	}
	return id, err
}

// SearchHelpDocInfo 获取帮助文档的详情
func (s *sHelpDoc) SearchHelpDocInfo(ctx context.Context, id string) (res *model.LotHelpDocInfoAndIdRes, err error) {
	r := g.RequestFromCtx(ctx)
	if err = dao.LotHelp.Ctx(ctx).Where("id", id).Scan(&res); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	if res == nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), "没有该文档")
	}
	return res, err
}

// HelpDocList 获取帮助文档的列表
func (s *sHelpDoc) HelpDocList(ctx context.Context, req *model.SearchHelpDocListReq) (res *model.HelpDocListRes, err error) {
	r := g.RequestFromCtx(ctx)
	helpDocList := make([]*model.LotHelpDocInfoAndIdRes, 0)
	startNum, endNum := paging.Paging(req.Paging)
	searchHelpDoc := g.Map{
		"help_class_type": req.HelpClassType,
	}
	if err = dao.LotHelp.Ctx(ctx).OmitEmpty().Where(searchHelpDoc).OrderDesc("updated_at").Limit(startNum, endNum).Scan(&helpDocList); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	// 获取总条数
	countInfo, err := dao.LotHelp.Ctx(ctx).OmitEmpty().Where(searchHelpDoc).Count()
	putCount := paging.PutCount(req.Paging, countInfo)
	res = &model.HelpDocListRes{
		List:    helpDocList,
		PutPage: *putCount,
	}
	return res, err
}
